
const { GameModel } = require("../model/gameModel");
const audio = require("../utils/audio");

cc.Class({
    extends: cc.Component,

    properties: {
        // 成语填充区
        phaseBlock: {
            type: cc.Node,
            default: null,
        },
        // 文字选择区
        cellSelect: {
            type: cc.Node,
            default: null,
        },
        // 返回按钮
        backHome: {
            type: cc.Node,
            default: null,
        },
        // 下一关提示
        gameOver: {
            type: cc.Node,
            default: null,
        },
        tips: {
            type: cc.Node,
            default: null
        },

        audioUtils: {
            type: audio,
            default: null,
        },

        // 关卡数
        level: {
            type: cc.Label,
            default: null,
        },
        gameModel: {
            type: cc.Object,
            default: null,
        },
        guideStep: {
            type: cc.Object,
            default: null,
        },

        // 引导的手型
        hand: {
            type: cc.Node,
            default: null,
        },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.gameModel = new GameModel();
        // 获取引导阶段
        this.guideStep = parseInt(cc.sys.localStorage.getItem("guideStep") || 1);
        cc.log("step", this.guideStep);
        this.gameModel.init();
        this.renderLevel();
        if (this.guideStep === 1) {
            this.hand.active = true;
            // 第一次引导, 先注册，否则 _touchListener 会报 null
            this.node.on(cc.Node.EventType.TOUCH_START, this.guideListener, this);
            this.guide();
        }
    },

    start () {
    },

    nextLevel() {
        this.renderLevel();
    },

    renderLevel() {
        this.gameModel.resetModel();
        this.gameModel.updatePhase();
        // TODO 间隔均匀
        this.level.string = `第${this.gameModel.level}关`;
        const phaseView = this.phaseBlock.getComponent("phaseView");
        phaseView.initWithModel(this, this.gameModel);
        const selectView = this.cellSelect.getComponent("selectView");
        selectView.initWithModel(this, this.gameModel);
        this.gameOver.active = false;
        this.phaseBlock.active = true;
        this.cellSelect.active = true;
        this.tips.active = true;
    },

    updateView() {
        const mainCell = this.gameModel.changeCells;
        const selectCell = this.gameModel.changeSelectCells;
        const t1 = this.getPlayAniTime(mainCell);
        const t2 = this.getPlayAniTime(selectCell);
        const t = Math.max(t1, t2);
        // phaseView
        this.phaseBlock.getComponent("phaseView").disableTouch(t);
        this.cellSelect.getComponent("selectView").disableTouch(t);
        this.phaseBlock.getComponent("phaseView").updateView(mainCell);
        this.cellSelect.getComponent("selectView").updateView(selectCell);
        this.gameModel.cleanChange();
        if (this.gameModel.isGameOver()) {
            this.gameOver.active = true;
            this.phaseBlock.active = false;
            this.cellSelect.active = false;
            this.tips.active = false;
            this.audioUtils.playFinish();
            this.gameModel.updateLevel();
        }
    },
    // 获取最大播放时间
    getPlayAniTime(cells) {
        let maxTime = 0;
        if(!cells) {
            return maxTime;
        }
        cells.forEach(elem => {
            elem.cmd.forEach(cmd => {
                if(maxTime < cmd.playTime) {
                    maxTime = cmd.playTime;
                }
            }, this)
        }, this);
        return maxTime;
    },

    update(dt) {
        // this.count++;
        // if(this.count % 60 === 0) {
        //     cc.log("selectCells =", this.gameModel.selectCells[1],  this.cellSelect.getComponent("selectView").cellViews);
        // }
    },

    quit2home() {
        // save level
        cc.sys.localStorage.setItem("level", this.gameModel.level);
        cc.director.loadScene("home");
    },

    guideListener(event) {
        // 触摸点在当前节点下的坐标
        const pos = this.node.convertToNodeSpaceAR(event.getLocation());
        // 坐标转换成世界坐标
        const worldPos = this.node.convertToWorldSpaceAR(pos);
        let rect;
        let touchPos;
        if (this.guideStep === 1) {
            // 将世界坐标转换成 phaseBlock 下的坐标
            touchPos = this.phaseBlock.convertToNodeSpaceAR(worldPos);
            const cell = this.gameModel.getInputCell(1);
            const phaseView = this.phaseBlock.getComponent("phaseView");
            rect = phaseView.cellViews[cell.x][cell.y].node.getBoundingBox();
        } else if (this.guideStep === 2) {
            // 选择格子
            touchPos = this.cellSelect.convertToNodeSpaceAR(worldPos);
            const selectView = this.cellSelect.getComponent("selectView");
            // 目前只有一个
            rect = selectView.cellViews[1][1].node.getBoundingBox();
        } else {
            this.node._touchListener.setSwallowTouches(false);
            return ;
        }
        // 判断触摸点是否在cell上
        if (rect.contains(touchPos)) {
            // 可以点击
            cc.log("enable touch");
            this.node._touchListener.setSwallowTouches(false);
            this.guideStep++;
            this.guide();
        } else {
            // 吞噬触摸，禁止触摸事件传递给按钮(禁止冒泡)
            this.node._touchListener.setSwallowTouches(true);
            cc.log("disable touch");
        }
    },

    setHand(pos) {
        // 引导手
        this.hand.setPosition(cc.v2(pos.x, pos.y - 70));
        const moveForward = cc.moveBy(0.9, cc.v2(0, 50));
        const moveBack = cc.moveBy(0.9, cc.v2(0, -50));
        const repeat = cc.repeatForever(cc.sequence(moveForward, moveBack));
        // 停止之前的动作
        this.hand.stopAllActions();
        this.hand.runAction(repeat);
    },

    // 引导
    guide() {
        // 第一步
        if (this.guideStep === 1) {
            const cell = this.gameModel.getInputCell(1);
            // 转换到世界坐标
            const convertPos =  this.phaseBlock.convertToWorldSpaceAR(cc.v2(cell.posX, cell.posY));
            // 从世界坐标转换到 canvas 的局部坐标
            this.setHand(this.node.convertToNodeSpaceAR(convertPos));
        } else if (this.guideStep === 2) {
            // 第二步
            // TODO 支持选择多个
            const selectView = this.cellSelect.getComponent("selectView");
            const cell = selectView.cellViews[1][1];
            const convertPos = this.cellSelect.convertToWorldSpaceAR(cell.node.position);
            this.setHand(this.node.convertToNodeSpaceAR(convertPos));
        } else {
            this.hand.active = false;
            cc.sys.localStorage.setItem("guideStep", this.guideStep.toString());
        }

    }

});